jsx3.require("jsx3.gui.Block");

/**
 * The Main AdminDesktop plugin container for the entire ActiveMatrix Admin UI.  This is the top-level container for
 * new perspectives.
 */
jsx3.Class.defineClass(
        "tibco.admin.AdminDesktop",
        jsx3.gui.Block,
        [tibco.admin.plugin.PluginContainerInterface],
        function (desktop) {

            /**
             * A reference to the plugin component class instance for the current perspective context
             *
             * @private
             */
            desktop.prototype.currentHandler = null;

            /**
             * A variable used for track user's work environment 
             *
             * @private
             */
            desktop.prototype.workEnvironment = null;


            desktop.prototype.init = function(strName, vntLeft, vntTop, vntWidth, vntHeight, strHTML) {
                this.jsxsuper(strName, vntLeft, vntTop, vntWidth, vntHeight, strHTML);
            }

            desktop.prototype.initialize = function() {
                // Load Dynamic properties for the component.xml files
                var me = this;
                tibco.admin.Main.initializePlugins(me, me.completeInitialization);
            }

            desktop.prototype.completeInitialization = function() {
                try {
                    tibco.admin.Main.setServer("APP.tibco.admin");
                    this.callsearchUsers();
                }
                catch(ex) {
                    tibco.admin.Main.logException(ex);
                }
                var server = tibco.admin.Main.getServer();
                var label = server.getJSXByName("blkStatus_00");
//                label.setText(server.getDynamicProperty("@Desktop Welcome Label") + " " + tibco.admin.Main.getUserName(), true);
                this.onReady();
            }

						desktop.prototype.callsearchUsers = function() {

				      var objService = tibco.admin.Main.loadService("tibco.admin",
				        "rules/showProfile.xml",
				        "searchUsers",
				        "searchUsers");

				       if(tibco.admin.Main.getServer().getEnv("MODE")) {
				            objService.setEndpointURL(tibco.admin.util.ServiceHelper.getUserMgtEndpointURL());
				       }

				      objService.gUserName = gUserName;
				      //subscribe
				      var me = this;
				      objService.subscribe(jsx3.net.Service.ON_SUCCESS,me, me.onsearchUsersSuccess);

				      objService.compile();

				      //call the service
				      objService.doCall();
				    };

				    desktop.prototype.onsearchUsersSuccess = function(objEvent) {

				    	var showProfile_009 = tibco.admin.Main.getServer().getCache().getDocument("showProfile_009");

				    	var myRecords = showProfile_009.selectNodes("/data/record");

				    	var myRecord = myRecords.get(0);

				    	var isWriteable_009 = myRecord.getAttribute("isWriteable_009");

				    	//if realms are read-only
							if(isWriteable_009 == 'false'){

              	var lblProfile_00 = tibco.admin.Main.getServer().getJSXByName("lblProfile_00");

              	lblProfile_00.setDisplay(jsx3.gui.Block.DISPLAYNONE,true);

            	}
				    };

            desktop.prototype.onReady = function() {
                this.tempBlock = new jsx3.gui.Block();
                if (this.getPluginList().size() == 0) {
                    var preLoad = new jsx3.util.List(0);


                    if (!tibco.admin.environments || !tibco.admin.environments.application) {
                        try {
                            tibco.admin.Main.loadClass("tibco/admin/environments/application.js", "tibco.admin");
                            preLoad.add(tibco.admin.environments.application, preLoad.size());
                        }
                        catch(ex) {
                            tibco.admin.Main.logException(ex);
                        }
                    }
                    else {
                        preLoad.add(tibco.admin.environments.application, preLoad.size());
                    }

                    if (!tibco.admin.environments || !tibco.admin.environments.approve) {
                        try {
                            tibco.admin.Main.loadClass("tibco/admin/environments/approve.js", "tibco.admin");
                            preLoad.add(tibco.admin.environments.approve, preLoad.size());
                        }
                        catch(ex) {
                            tibco.admin.Main.logException(ex);
                        }
                    }
                    else {
                        preLoad.add(tibco.admin.environments.approve, preLoad.size());
                    }
/*
                    if (!tibco.admin.deployment || !tibco.admin.deployment.Deploy) {
                        try {
                            tibco.admin.Main.loadClass("tibco/admin/deployment/Deploy.js", "tibco.admin");
                            preLoad.add(tibco.admin.deployment.Deploy, preLoad.size());
                        }
                        catch(ex) {
                            tibco.admin.Main.logException(ex);
                        }
                    }
                    else {
                        preLoad.add(tibco.admin.deployment.Deploy, preLoad.size());
                    }

                    if (!tibco.admin.monitormanage || !tibco.admin.monitormanage.framework || !tibco.admin.monitormanage.framework.mainPage || !tibco.admin.monitormanage.framework.mainPage.MainPage) {
                        try {
                            tibco.admin.Main.loadClass("tibco/admin/monitormanage/framework/mainPage/MainPage.js", "tibco.admin");
                            preLoad.add(tibco.admin.monitormanage.framework.mainPage.MainPage, preLoad.size());
                        }
                        catch(ex) {
                            tibco.admin.Main.logException(ex);
                        }
                    }
                    else {
                        preLoad.add(tibco.admin.monitormanage.framework.mainPage.MainPage, preLoad.size());
                    }
*/
                    this.loadPlugins("tibco.admin.plugin.SelectPerspectiveInterface", preLoad);
                }
                else {
                    this.onAfterGetPlugins();
                }
            }

            /**
             * Loads the components into the UI Framework by adding them to the first extension point (the perspective
             * select box).
             *
             * @private
             */
            desktop.prototype.loadComponents = function(response) {
                // Use a hack way to customize the select box look like
                var selPerspective = tibco.admin.Main.getServer().getJSXByName("selPerspectiveSelect_00");
                var selPerspectiveHTML = selPerspective.getRendered();
                selPerspectiveHTML.firstChild.firstChild.style.paddingTop = 0;
                selPerspectiveHTML.style.backgroundImage = tibco.admin.Main.getServer().getDynamicProperty("@addin@Arrow For Header");
                selPerspective.setDisplay(jsx3.gui.Block.DISPLAYBLOCK,true);

                if (response.status == "SUCCESS") {
                    var welcomePage = this.getDescendantOfName("blkWelcomePage_00");

                    this.perspectiveSelect = response.obj;
                    var me = this;
                    this.perspectiveSelect.registerWithPluginContainer(me);
                    var iter = this.getPluginList("tibco.admin.Desktop03").iterator();
                    while (iter.hasNext()) {
                        var obj = iter.next();
                        var strRECORDID = this.perspectiveSelect.addItemToSelectBox(obj.getSelectText(), obj);
                    }
                }
                else {
                    if (response.exception) {
                        tibco.admin.Main.logException(response.exception, response.message);
                    }
                    else {
                        jsx3.log(response.message);
                    }
                }
            }

            desktop.prototype.performPerspectiveChange = function(obj) {
                var block = tibco.admin.Main.getServer().getJSXByName("blkPerspectiveSubSelect_00");
                try {
                    block.removeChildren();
                } catch(ex1) {
                    tibco.admin.Main.logException(new jsx3.lang.Exception("Error removing sub-selection content", jsx3.NativeError.wrap(ex1)));
                }
                if (this.currentHandler) {
                    try {
                        this.currentHandler.unload();
                    }
                    catch(ex) {
                        tibco.admin.Main.logException(new jsx3.lang.Exception("Error unloading content for " + this.currentHandler, jsx3.NativeError.wrap(ex)));
                    }
                }
                this.currentHandler = obj;
                //                var sectionLabel = tibco.admin.Main.getServer().getJSXByName("lblSectionTitle_00");
                //                sectionLabel.setText("", true);
                var labelObj = tibco.admin.Main.getServer().getJSXByName("lblPerspectiveSubSelect_00");
                var textVal = obj.getSecondarySelectionText();
                if (!textVal) {
                    textVal = "";
					this.getDescendantOfName("blkPerspectiveDisplay_00").removeChildren();
                }
                else if (textVal != "") {
                    textVal += ":";
					if (!this.getDescendantOfName("blkWelcomePage_00"))
					{
						this.getDescendantOfName("blkPerspectiveDisplay_00").removeChildren();
					}
                }
                labelObj.setText(textVal, true);
                obj.loadComponent(block);
            }

            desktop.prototype.cancelPerspectiveChange = function(obj) {
                this.perspectiveSelect.revertSelection();
            }

            /**
             * Called by the perspective select box to indicate a perspective was selected.  Notifies the plugin component
             *that it may load it's secondary selection UI into the second extension point.
             *
             * @param obj {Object} the implementation class instance for the perspective plugin component that
             *            was selected.
             *
             * @private
             */
            desktop.prototype.itemSelected = function(obj) {
                var me = this;
                if (this.currentHandler) {
                    try {
                        this.currentHandler.allowComponentUnload(me, me.performPerspectiveChange, me.cancelPerspectiveChange, obj);
                    } catch(ex) {
                        tibco.admin.Main.logException(ex);
                        this.performPerspectiveChange(obj);
                    }
                }
                else {
                    this.performPerspectiveChange(obj);
                }
            }

            /**
             * The callback function used by perspective plugin components to indicate when their secondary selection
             * has been performed, and they are ready to load the main perspective into the thrid extension point (the
             * main perspective viewing area).  Handles removal of the previous perspective, then notified the plugin
             * component that it may load it's main perspective viewing area into the third extension point.
             *
             * @param obj {Object} the object selected by the plugin compomnent in the secondary selection; passed back
             *            to the plugin component when it is notified that it may load it's main perspective viewing
             *            area into the third extension point.
             *
             * @private
             */
            desktop.prototype.stage2ItemSelected = function(obj) {
                if (obj) {
                    this.workEnvironment = obj;
                }
                var parent = tibco.admin.Main.getServer().getJSXByName("blkPerspectiveDisplay_00");
                parent.removeChildren();
                //                var sectionLabel = tibco.admin.Main.getServer().getJSXByName("lblSectionTitle_00");
                var textVal = this.currentHandler.getSectionTitle(obj);
                if (!textVal || (textVal == "")) {
                    textVal = tibco.admin.Main.getServer().getDynamicProperty("@Desktop Default Config Label");
                }
                //                sectionLabel.setText(textVal, true);

                this.currentHandler.loadStage2Component(parent, obj);
                parent.repaint();
            }

            /**
             * Called when the component should be destroyed.
             *
             * @private
             */
            desktop.prototype.destroyMe = function() {
                var iter = this.getPluginList().iterator();
                while (iter.hasNext()) {
                    try {
                        iter.next().destroyPlugin();
                    }
                    catch(ex) {
                        tibco.admin.Main.logException(ex);
                    }
                }
                this.getPluginList().clear();
            }


            desktop.prototype.setupPlugin = function(obj) {
                obj.callbackTarget = this;
                obj.selectionCallback = this.stage2ItemSelected;
            }

            desktop.prototype.onAfterGetPlugins = function() {
                var me = this;
                tibco.admin.Main.loadUIResourceAsync(this.getDescendantOfName("blkPerspectiveSelect_00"), "tibco.admin", "components/perspectiveSelect.xml", me, me.loadComponents, true);
            }

            // jump to the logout.jsp directly,no need to confirm,modified in 2007-Jun-29
            desktop.onClickLogOut = function() {
                window.top.location.href = "logout.jsp";
                //var confirmLogOut = tibco.admin.Main.getServer().getDynamicProperty("@addin@confirmLogOut");
                //tibco.admin.Main.getServer().confirm("Logout", confirmLogOut , desktop.onClickLogOut_OnOk ,desktop.onClickLogOut_OnCancel, "Yes", "No") ;
            }

            desktop.onClickLogOut_OnOk = function(objDialog) {
                objDialog.doClose();
                window.top.location.href = "logout.jsp";
            }

            desktop.onClickLogOut_OnCancel = function(objDialog) {
                objDialog.doClose();
                return false;
            }

            desktop.onClickReturnToLogin = function() {
                window.top.location.href = "logout.jsp";
            }


			desktop.prototype.lblApplication_OnClick = function() {
				this.getDescendantOfName("lblApplication").setColor("#F9DB6D").repaint();
				this.getDescendantOfName("lblApprove").setColor("#BDE0EA").repaint();
				this.getDescendantOfName("lblSystem").setColor("#BDE0EA").repaint();

				/*var selPerspective = tibco.admin.Main.getServer().getJSXByName("selPerspectiveSelect_00");
				selPerspective.setValue("1");
				selPerspective.doEvent(jsx3.gui.Interactive.SELECT, {strRECORDID: "1"});
                */
                var parent = tibco.admin.Main.getServer().getJSXByName("blkPerspectiveDisplay_00");
                try{
                    parent.removeChildren();
                } catch(ex) {
                }
                tibco.admin.environments.application.getInstance().loadComponent(parent);
			}

			desktop.prototype.lblApprove_OnClick = function() {
				this.getDescendantOfName("lblApprove").setColor("#F9DB6D").repaint();
				this.getDescendantOfName("lblApplication").setColor("#BDE0EA").repaint();
				this.getDescendantOfName("lblSystem").setColor("#BDE0EA").repaint();

				//var selPerspective = tibco.admin.Main.getServer().getJSXByName("selPerspectiveSelect_00");
				//selPerspective.setValue("2");
				//selPerspective.doEvent(jsx3.gui.Interactive.SELECT, {strRECORDID: "2"});
                var parent = tibco.admin.Main.getServer().getJSXByName("blkPerspectiveDisplay_00");
                try{
                    parent.removeChildren();
                } catch(ex) {
                }
                tibco.admin.environments.approve.getInstance().loadComponent(parent);
			}

			desktop.prototype.lblSystem_OnClick = function() {
				this.getDescendantOfName("lblSystem").setColor("#F9DB6D").repaint();
				this.getDescendantOfName("lblApplication").setColor("#BDE0EA").repaint();
				this.getDescendantOfName("lblApprove").setColor("#BDE0EA").repaint();

				this.getDescendantOfName("blkPerspectiveDisplay_00").removeChildren();

				var dlgSetPermissions = APP.tibco.admin.getBodyBlock().load(
						"tibco/admin/enterpriseAssets/userMgt/window/permissions/ui/addUsersNGroups.xml");

				dlgSetPermissions.setPermission("UDDIServer", 1, 1);

			}
        });
